package com.website.at.fw.dao.ibatis;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.website.at.fw.dao.IQueryDao;
import com.website.at.fw.dao.IllegalClassTypeException;

/**
 * 查询系用Dao实现
 * 
 * @author kongld
 */
public class QueryDaoIBatisImpl extends SqlMapClientDaoSupport implements IQueryDao {

	static Log log = LogFactory.getLog(QueryDaoIBatisImpl.class);

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public <E> E executeForObject(String sqlID, Object bindParams, Class clazz) {
		if (log.isDebugEnabled()) {
			log.debug("executeForObject Start.");
		}

		SqlMapClientTemplate sqlMapClientTemplate = getSqlMapClientTemplate();
		Object obj = sqlMapClientTemplate.queryForObject(sqlID, bindParams);

		if (log.isDebugEnabled() && obj != null) {
			log.debug("Return type:" + obj.getClass().getName());
		}

		E rObj = null;
		try {
			if (clazz != null && obj != null) {
				rObj = (E) clazz.cast(obj);
			}
		} catch (ClassCastException e) {
			log.error(IllegalClassTypeException.ERROR_ILLEGAL_CLASS_TYPE);
			throw new IllegalClassTypeException(e);
		}

		if (log.isDebugEnabled()) {
			log.debug("executeForObject End.");
		}

		return rObj;
	}


	@SuppressWarnings("unchecked")
	@Override
	public <E> List<E> executeForObjectList(String sqlID, Object bindParams) {
		if (log.isDebugEnabled()) {
			log.debug("executeForObjectList Start.");
		}

		SqlMapClientTemplate sqlMapClientTemplate = getSqlMapClientTemplate();
		List<E> list = (List<E>) sqlMapClientTemplate.queryForList(sqlID, bindParams);

		if (log.isDebugEnabled()) {
			log.debug("executeForObjectList End.");
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <E> List<E> executeForObjectList(String sqlID, Object bindParams, int beginIndex, int maxCount) {
		if (log.isDebugEnabled()) {
			log.debug("executeForObjectList Start.");
		}

		SqlMapClientTemplate sqlMapClientTemplate = getSqlMapClientTemplate();
		List<E> list = (List<E>) sqlMapClientTemplate.queryForList(sqlID, bindParams, beginIndex, maxCount);

		if (log.isDebugEnabled()) {
			log.debug("executeForObjectList End.");
		}
		
		return list;
	}
}
